import { getUserInfo } from "@/api/my";
import { loginByWxMa } from "../api/login";

/*
 * @Author: fengYM feng25321@163.com
 * @Date: 2023-09-21 16:09:36
 * @LastEditors: fengYM feng25321@163.com
 * @LastEditTime: 2023-09-25 11:34:09
 * @Description:
 */
export default {
  data() {
    return {};
  },
  onLoad: function () {
    let thePages: any = getCurrentPages();
    let thePage = thePages[thePages.length - 1];
    let newArr = thePage.route.split("/");
    let pageName = newArr[newArr.length - 1];
    let arr: string[] = ["orderDetails", "factoryDetails", "InviteFriends"];
    if (arr.some((condition) => pageName.includes(condition))) {
      //@ts-ignore
      wx.showShareMenu({
        withShareTicket: true,
        menus: ["shareAppMessage", "shareTimeline"],
      });
    } else {
      //@ts-ignore
      wx.hideShareMenu();
    }
  },
  onShareAppMessage(res: { from: string }) {
    console.log(res, "onShareAppMessage");
    let that: any = this;
    let imageUrl = that.shareUrl || "";
    if (res.from === "button") {
      //这块需要传参，不然链接地址进去获取不到数据
      let path = `/` + that.$scope.route + `?item=` + that.$scope.options.item;
      return {
        title: "",
        path: path,
        imageUrl: imageUrl,
      };
    }
    if (res.from === "menu") {
      console.log(that.$scope.options, "13131");
      console.log(uni.getStorageSync("userInfo"));

      let keys = that.$scope.options;
      keys.invitationCode = uni.getStorageSync("userInfo").invitationCode;
      let path = `/${that.$scope.route}?`;
      for (const key of Object.keys(keys)) {
        path += `${key}=${keys[key]}`;
        // 添加 '&' 分隔符，除非是最后一个属性
        if (key !== Object.keys(keys)[Object.keys(keys).length - 1]) {
          path += "&";
        }
      }
      console.log(path, "path");

      return {
        title: "",
        path: path,
      };
    }
  },
  // 分享到朋友圈
  onShareTimeline() {
    let that: any = this;
    const keys = Object.keys(that.$scope.options)[0];
    return {
      title: "",
      path: `/${that.$scope.route}?${keys}=${that.$scope.options[keys]}`,
    };
  },
};

export const TanPreviewImage = (imgs: any, iIndex: any) => {
  let images = [];
  images = [...imgs];
  uni.previewImage({
    current: iIndex,
    urls: images,
    longPressActions: {
      //长按保存图片到相册
      itemList: ["保存图片"],
      success: (data) => {
        uni.saveImageToPhotosAlbum({
          //保存图片到相册
          filePath: "payUrl",
          success: function () {
            uni.showToast({ icon: "success", title: "保存成功" });
          },
          fail: (err) => {
            uni.showToast({ icon: "none", title: "保存失败，请重新尝试" });
          },
        });
      },
    },
  });
};
export const goBack = () => {
  if (getCurrentPages().length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({
      url: "/pages/home/home",
    });
  }
};
export const goPage = (url: string) => {
  uni.navigateTo({
    url,
  });
};
export const loginFn = () => {
  return new Promise(async (resolve1, reject2) => {
    const provider: any = await new Promise((resolve, reject) => {
      uni.getProvider({
        service: "oauth",
        success: function (res) {
          resolve(res);
        },
        fail: function (err) {
          reject(err);
        },
      });
    });

    // 当前只做微信小程序
    if (!~provider.provider.indexOf("weixin")) return;
    const loginRes: any = await new Promise((resolve, reject) => {
      uni.login({
        provider: "weixin",
        success: function (res) {
          resolve(res);
        },
        fail: function (err) {
          reject(err);
        },
      });
    });
    // 前端获取到微信登录临时码，传至后台换openId和sessionId
    let code = loginRes.code;
    console.log(uni.getStorageSync("invitationCode"), "login");

    const {
      data: { token },
    } = await loginByWxMa({ code, invitationCode: uni.getStorageSync("invitationCode") || "" });
    uni.setStorageSync("token", token);
    resolve1(1);
  });
};
export const formatRichText = (html: any) => {
  if (!html) {
    return "";
  }
  // html 就是你要传进来地富文本参数
  // 去掉img标签里的style、width、height属性
  let newContent = html.replace(/<img[^>]*>/gi, function (match: any) {
    match = match.replace(/style="[^"]+"/gi, "").replace(/style='[^']+'/gi, "");
    match = match.replace(/width="[^"]+"/gi, "").replace(/width='[^']+'/gi, "");
    match = match.replace(/height="[^"]+"/gi, "").replace(/height='[^']+'/gi, "");
    return match;
  });
  // 修改所有style里的width属性为max-width:100%
  newContent = newContent.replace(/style="[^"]+"/gi, function (match: any) {
    match = match.replace(/width:[^;]+;/gi, "max-width:100%;").replace(/width:[^;]+;/gi, "max-width:100%;");
    return match;
  });
  // 去掉<br/>标签
  newContent = newContent.replace(/<br[^>]*\/>/gi, "");
  // img标签添加style属性：max-width:100%;height:auto
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0px auto;"'); // 返回 处理后地结果
  return newContent;
};
export const getTopHeight = () => {
  let custom = uni.getMenuButtonBoundingClientRect(); // 小程序右上角胶囊信息
  let system: any = uni.getSystemInfoSync(); // 获取设备信息
  let navHeight = system.statusBarHeight + 44;
  let customTop = custom.top;
  let customRight = custom.left;
  return {
    /**
     * 导航栏的高度
     */
    navHeight,
    /**
     * 胶囊按钮与顶部的距离
     */
    customTop,
    /**
     *  胶囊按钮与右侧的距离
     */
    customRight,
  };
};
